//
//  WBStatusListViewModel.swift
//  daoge_sineweibo
//
//  Created by 伍禄林 on 16/9/29.
//  Copyright © 2016年 伍禄林. All rights reserved.
//

import Foundation
import SDWebImage

let MAX_ERROR_TIMES = 3
class WBStatusListViewModel {
    
    lazy var statusList =  [WBStatusViewModel]()
    var errorTimes = 0
    /// 加载微博数据
    ///
    /// - parameter completion: 请求完成回调
    
    func loadStatus(isPull: Bool, completion: @escaping (_ isSuccess: Bool, _ hasMoreDate: Bool) -> ())   {
        
        if isPull && errorTimes > MAX_ERROR_TIMES {
            
            completion(false,false)
            
            return
        }
        
        let since_id = isPull ? 0 : statusList.first?.status.id ?? 0
        
        let max_id = !isPull ? 0 : statusList.last?.status.id ?? 0
        
        
        WBNetworkingManager.shared.statiList(since_id: since_id, max_id: max_id){(json, isSuccess) in
            
            if !isSuccess {
                
                completion(false, false)
                
                return
            }
            
            var array = [WBStatusViewModel]()
            
            for dict in json {
                
                guard let status = WBStatusModel.yy_model(with: dict) else {
                    continue
                }
                
                let statusViewModel = WBStatusViewModel(model: status)
                
                print("array=====\(array)")
                array.append(statusViewModel)
                
            }
            
            if isPull {
                
                self.statusList += array
                
            }else {
                self.statusList = array + self.statusList
            }
            
            if isPull && array.count == 0 {
                
                self.errorTimes += 1
                
                completion(isSuccess,false)
            }else {
                
                self.cacheSingleImage(list: array) {(length: Int) in
                    
                     print("缓存图像的大小＝11111＝＝\(length / 1024) k")
                    
                    completion(isSuccess,true)
                }
            }
        }
        
    }
    
    //缓存本次下载微博数组中的单张图像
    private func cacheSingleImage(list: [WBStatusViewModel],cacheCompletion: @escaping (_ length: Int) -> ()) {
        
        var length = 0
        
        let group = DispatchGroup()
        
        for vm in list {
            
            if vm.picUrls?.count != 1 {
                continue
            }
            
            guard let pic = vm.picUrls?[0].thumbnail_pic,
                let url = URL(string: pic) else {
                    continue
            }
            
            print("要缓存的url＝＝\(url)")
            
            //下载图片到沙河 名字是图片url 加 md5
            //沙河缓存
            group.enter()
            
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, _) in
                
                if let image = image,
                    let data = UIImagePNGRepresentation(image) {
                    
                    length += data.count
                    
                    vm.updataSinglePicSize(image: image)
                }
                
                group.leave()
            })
        }
        
        group.notify(queue: DispatchQueue.main) { 
            
            print("缓存图像的大小＝＝＝\(length / 1024) k")
            cacheCompletion(length)
            
        }
    }
    
}
